package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xgm
 * @date 2020/11/21
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //调用Dao层查询数据
        Page<Permission> page = permissionDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional
    @Override
    public void add(Permission permission) {
        log.info("[权限-新增]data：{}",permission);
        permissionDao.insert(permission);
    }

    @Transactional
    @Override
    public void delete(Integer id) {
        log.info("[删除权限]id:{}",id);
        //校验是否可以删除  如果有与这个权限绑定的角色则不能删除
        //先按照这个Id在t_role_permission查找有没有role
        Long count = permissionDao.countRoleByPermissionId(id);
        if (count > 0){
            throw new BusinessRuntimeException("当前权限有角色，不能删除");
        }
        //校验完再删
        permissionDao.delete(id);
    }


    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Transactional
    @Override
    public void edit(Permission permission) {
        log.info("[检查项-编辑]data:{}",permission);
        permissionDao.update(permission);
    }


}
